// ThreadSynchronization.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <Windows.h>
#include <iostream>
#include"../Common/CppThread.h"


HANDLE hEvent1;  //can synch cross processor
HANDLE hEvent2;

class Thread1 : public CppThread
{
public:
    Thread1(int* var)
    {
        _cnt = var;
    }

protected:
    virtual void run()
    {
        while (!IsDone())
        {
            WaitForSingleObject(hEvent1, INFINITE);
            ++(*_cnt);
            printf("thread1:%d\n", *_cnt);
            SetEvent(hEvent2);
        }
    }

private:
    int* _cnt;
};

class Thread2 : public CppThread
{
public:
    Thread2(int* var)
    {
        _cnt = var;
    }

protected:
    virtual void run()
    {
        while (!IsDone())
        {
            WaitForSingleObject(hEvent2, INFINITE);
        ++(*_cnt);
        printf("thread2:%d\n", *_cnt);
        SetEvent(hEvent1);
        }

    }

private:
    int* _cnt;
};

int main()
{
    hEvent1 = CreateEvent(NULL, FALSE, FALSE, L"event1");//if have same name, system treat two handle as same, although address is different
    hEvent2 = CreateEvent(NULL, FALSE, FALSE, L"event2");
    int counter = 0;
    Thread1 t1(&counter);
    Thread2 t2(&counter);

    SetEvent(hEvent1);
    t1.start();
    t2.start();

    getchar();
    t1.SetDone();
    t2.SetDone();
    t1.join();
    t2.join();

    std::cout << "Hello World!\n";
    CloseHandle(hEvent1);
    CloseHandle(hEvent2);
}

// Run program: Ctrl + F5 or Debug > Start Without Debugging menu
// Debug program: F5 or Debug > Start Debugging menu

// Tips for Getting Started: 
//   1. Use the Solution Explorer window to add/manage files
//   2. Use the Team Explorer window to connect to source control
//   3. Use the Output window to see build output and other messages
//   4. Use the Error List window to view errors
//   5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project
//   6. In the future, to open this project again, go to File > Open > Project and select the .sln file
